package com.sky.service.user.impl;

import com.alibaba.fastjson.JSONObject;
import com.sky.dto.UserLoginDTO;
import com.sky.exception.BaseException;
import com.sky.mapper.user.MerchantMapper;
import com.sky.mapper.user.UserMapper;
import com.sky.pojo.Merchant;
import com.sky.pojo.User;
import com.sky.properties.JwtProperties;
import com.sky.service.user.UserLoginService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.JwtUtil;
import com.sky.utils.MapUtils;
import com.sky.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private JwtProperties jwtProperties;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MerchantMapper merchantMapper;
    private static final String URL="https://api.weixin.qq.com/sns/jscode2session";
    @Value("${sky.wechat.appid}")
    private String appid;
    @Value("${sky.wechat.secret}")
    private String secret;
    @Override
    public UserLoginVO login(UserLoginDTO userLoginDTO) {
        //1. 获取openid
        String openId = getOpenId(userLoginDTO.getCode());
        log.debug("openid为：{}",openId);
        //2. 判断openid是否为空
        if (!StringUtils.hasText(openId)){
            throw new BaseException("未获取到openid");
        }
        //3. 根据openid判断用户是否在数据库中
        User user = userMapper.findByOpenId(openId);
        if (user==null){
            //4. 如果不存在，则创建新用户
            user = new User();
            user.setOpenid(openId);
            user.setCreateTime(LocalDateTime.now());
            userMapper.save(user);
        }
        //5.如果查询到，根据id生成token，返回给前端
        Map<String,Object> param = new HashMap<>();
        param.put("openid",openId);
        param.put("userId",user.getId());
        String token = JwtUtil.createJWT(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), param);

        Merchant merchant = merchantMapper.findById(1L);
        String lnglat = MapUtils.addressToLnglat(merchant.getShopAddress());
        BigDecimal cost = MapUtils.getDelivoryCost(lnglat,userLoginDTO.getLocation());

        //6. 组合返回对象
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .openid(openId)
                .token(token)
                .shopName(merchant.getShopName())
                .shopTelephone(merchant.getShopTelephone())
                .shopId(merchant.getId())
                .shopAddress(merchant.getShopAddress())
                .id(user.getId())
                .deliveryFee(cost)
                .build();
        return userLoginVO;
    }

    private String getOpenId(String code){
        Map<String,String> param = new HashMap<>();
        param.put("appid",appid);
        param.put("secret",secret);
        param.put("js_code",code);
        param.put("grant_type","authorization_code");

        String response = HttpClientUtil.doGet(URL,param);
        log.debug("获取到:{}",response);
        JSONObject jsonObject = JSONObject.parseObject(response);
        return (String) jsonObject.get("openid");
    }
}
